package com.linkoog.devtools.code_generator.wizard.generate.database.table.dialog.datasource.panel;

import com.linkoog.devtools.code_generator.database.domain.ConnectionInfo;
import com.linkoog.devtools.code_generator.database.domain.DbType;
import com.linkoog.devtools.code_generator.setting.persistent.CodeGenDevToolsPersistent;
import com.linkoog.devtools.code_generator.template.model.node.TemplateNodeData;
import com.intellij.openapi.actionSystem.ActionToolbarPosition;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ui.JBUI;
import com.linkoog.devtools.code_generator.wizard.code_database.ui.database.dialog.datasource.panel.DatasourceTreeCellRender;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.function.Consumer;

public class LeftPanelBuilder {

    private JPanel myMainPanel;

    private JPanel datasourceTreePanel;
    private JTree datasourceTree;

    private ToolbarDecorator toolbarDecorator;

    private Consumer<ConnectionInfo> connectionInfoConsumer;

    public LeftPanelBuilder() {
        myMainPanel.setMinimumSize(JBUI.size(185, -1));
        myMainPanel.setPreferredSize(JBUI.size(185, -1));

        initDatasourceTreePanel();
    }

    private void initDatasourceTreePanel() {
        initTemplateTree();
        initToolbarDecorator();

        datasourceTreePanel = toolbarDecorator.createPanel();
        //datasourceTreePanel.setPreferredSize(JBUI.size(160, -1));
        this.myMainPanel.add(datasourceTreePanel, BorderLayout.CENTER);
    }


    public JPanel getMyMainPanel() {
        return myMainPanel;
    }

    private void createUIComponents() {

    }

    public JTree getDatasourceTree() {
        return datasourceTree;
    }

    public ToolbarDecorator getToolbarDecorator() {
        return toolbarDecorator;
    }

    public Consumer<ConnectionInfo> getConnectionInfoConsumer() {
        return connectionInfoConsumer;
    }

    public void setConnectionInfoConsumer(Consumer<ConnectionInfo> connectionInfoConsumer) {
        this.connectionInfoConsumer = connectionInfoConsumer;
    }

    private void initToolbarDecorator() {
        toolbarDecorator = ToolbarDecorator.createDecorator(datasourceTree);
        toolbarDecorator.setToolbarPosition(ActionToolbarPosition.RIGHT);
        toolbarDecorator.setAddAction(anActionButton -> {
            DefaultTreeModel model = (DefaultTreeModel) datasourceTree.getModel();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

            ConnectionInfo connectionInfo = defaultConnectionInfo();
            DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(connectionInfo);
            model.insertNodeInto(treeNode, root, root.getChildCount());
            datasourceTree.setSelectionPath(new TreePath(treeNode.getPath()));

            List<ConnectionInfo> connList = CodeGenDevToolsPersistent.getInstance().getConnectionInfoList();
            connList.add(connectionInfo);

            resetConnectionInfoPanel(connectionInfo);
        });

        toolbarDecorator.setRemoveAction(anActionButton -> {
            DefaultTreeModel defaultTreeModel = (DefaultTreeModel) datasourceTree.getModel();
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) datasourceTree.getLastSelectedPathComponent();
            if (selectedNode.isRoot() || selectedNode == null) {
                return;
            }

            Object obj = selectedNode.getUserObject();
            if (!(obj instanceof ConnectionInfo)) {
                defaultTreeModel.removeNodeFromParent(selectedNode);
                return;
            }

            ConnectionInfo info = (ConnectionInfo) obj;
            int result = Messages.showYesNoDialog(info.getName(), "确认删除？", Messages.getQuestionIcon());
            if (result == Messages.YES) {
                defaultTreeModel.removeNodeFromParent(selectedNode);
                List<ConnectionInfo> connList = CodeGenDevToolsPersistent.getInstance().getConnectionInfoList();
                int i = connList.indexOf(info);
                if (i != -1) {
                    connList.remove(info);
                }

                resetConnectionInfoPanel(null);
            }
        });

    }

    private void resetConnectionInfoPanel(ConnectionInfo info) {
        Consumer<ConnectionInfo> connectionInfoConsumer = getConnectionInfoConsumer();
        if (connectionInfoConsumer != null) {
            connectionInfoConsumer.accept(info);
        }
    }


    private void initTemplateTree() {
        datasourceTree = new Tree();
        datasourceTree.putClientProperty("JTree.lineStyle", "Horizontal");
        datasourceTree.setRootVisible(false);
        datasourceTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        datasourceTree.setCellRenderer(new DatasourceTreeCellRender());
        datasourceTree.setEditable(false);


        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
        DefaultTreeModel model = new DefaultTreeModel(rootNode);


        List<ConnectionInfo> connList = CodeGenDevToolsPersistent.getInstance().getConnectionInfoList();
        for (int i = 0; i < connList.size(); i++) {
            ConnectionInfo connectionInfo = connList.get(i);
            DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(connectionInfo);
            rootNode.add(treeNode);
        }


        datasourceTree.setModel(model);
        //datasourceTree.setSelectionPath(new TreePath(fristNode.getPath()));

        //templateTree.addMouseListener(new MyTreePopupMenuActionListener());

        //节点选择事件
        /*templateTree.addTreeSelectionListener( it -> {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) templateTree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            Object object = node.getUserObject();
            if(object instanceof TemplateNodeData) {
                TemplateNodeData templateNodeData = (TemplateNodeData) object;
                templateSettingPanel.showTemplateRootPanel(templateNodeData);
            } else {
            }
        });*/


        datasourceTree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = datasourceTree.getRowForLocation(e.getX(), e.getY());
                datasourceTree.setSelectionRow(row);
                if (row == -1) {
                    resetConnectionInfoPanel(null);
                    return;
                }

                datasourceTree.setSelectionRow(row);
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) datasourceTree.getLastSelectedPathComponent();
                Object selectedNodeObject = selectedNode.getUserObject();
                if (selectedNodeObject == null) {
                    return;
                }


                if (SwingUtilities.isLeftMouseButton(e)) {
                    if (!isDoubleClick(e)) {
                        //鼠标左键--单击
                        if (selectedNodeObject instanceof ConnectionInfo) {
                            ConnectionInfo connectionInfo = (ConnectionInfo) selectedNodeObject;
                            resetConnectionInfoPanel(connectionInfo);
                        }
                    } else {
                        //鼠标左键--双击
                    }
                } else if (SwingUtilities.isRightMouseButton(e)) {
                    //鼠标右键--显示菜单
                    if (selectedNodeObject instanceof TemplateNodeData) {
                        //root节点
                    }
                }
            }
        });
    }

    private ConnectionInfo defaultConnectionInfo() {
        ConnectionInfo connectionInfo = new ConnectionInfo();

        DbType dbType = DbType.MYSQL;
        connectionInfo.setName("conn-" + CodeGenDevToolsPersistent.getInstance().nextConnNameIndex()).setDescription("").setDbType(dbType).setHost(dbType.getDefaultHost()).setPort(Integer.valueOf(dbType.getDefaultPort())).setUsername(dbType.getDefaultUser()).setPasswd("").setDatabase(dbType.getDefaultDatabase()).setSchema(dbType.getDefaultSchema());
        return connectionInfo;
    }

    public static boolean isDoubleClick(MouseEvent e) {
        return e != null && e.getClickCount() > 0 && e.getClickCount() % 2 == 0;
    }


    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        myMainPanel = new JPanel();
        myMainPanel.setLayout(new BorderLayout(0, 0));
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return myMainPanel;
    }


}
